package com.iseastar.guojiang.team;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CourierTeamDetailBackBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.team.fragment.TeamCenterDetailMonthOrderNumFragment;
import com.iseastar.guojiang.view.AppTab1;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.DateUtils;
import com.shouhuobao.take.weight.CircularImage;

import droid.frame.activity.title.TitleRes;
import droid.frame.ui.utils.Utils;
import droid.frame.utils.GlideUtil;
import droid.frame.view.ViewPagerExt;

/**
 * @author 李澄锋<br>
 * 2018/6/11
 * 火箭侠战队中心详情，分为 组队中和运营中战队
 */
public class CourierTeamCenterDetailActivity extends BaseActivity2 implements View.OnClickListener {

    private int type;//0 组队中  1 查看个人战队详情
    private BaseFragment[] mFragments = new BaseFragment[3];
    private TextView mOldAchievementTV;//过往成就
    private ViewGroup mCreatingTeamLayout;//组队中布局
    private ViewGroup mOperateTeamLayout;//运营中布局
    private ViewGroup mMemberApplyListLayout;//队员申请信息
    private ViewPagerExt mViewPager = null;
    private int teamId;

    private boolean isRequest = false;

    private CountDownTimer timer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        teamId = getIntent().getIntExtra("teamId", 0);
        type = getIntent().getIntExtra("type", 0);
        super.onCreate(savedInstanceState);
        if (type == 1) {
            mOldAchievementTV.setVisibility(View.VISIBLE);
            mOldAchievementTV.setOnClickListener(this);
            mCreatingTeamLayout.setVisibility(View.GONE);
            mOperateTeamLayout.setVisibility(View.VISIBLE);

        } else {
            mOldAchievementTV.setVisibility(View.GONE);
            mCreatingTeamLayout.setVisibility(View.VISIBLE);
            mOperateTeamLayout.setVisibility(View.GONE);
        }
        showLoadingDialog(null);
        AppHttp.getInstance().getTeamDetail(teamId);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_courier_team_detail);
        super.findViewById();
        getAppTitle().setCommonTitle("战队中心");
        mOldAchievementTV = findViewById(R.id.old_achievement_tv);
        mCreatingTeamLayout = findViewById(R.id.creating_team_layout);
        mOperateTeamLayout = findViewById(R.id.operate_team_layout);
        mMemberApplyListLayout = findViewById(R.id.team_applylist_layout);
        mMemberApplyListLayout.setOnClickListener(this);
        TextView[] mTags = new TextView[3];
        mTags[0] = findViewById(R.id.courier_team_detail_tab1);
        mTags[1] = findViewById(R.id.courier_team_detail_tab2);
        mTags[2] = findViewById(R.id.courier_team_detail_tab3);
        initFragment();

        mViewPager = findViewById(R.id.view_pager);
        ImageView mImgLine = findViewById(R.id.line_img);
        mViewPager.setFragmentItems(getSupportFragmentManager(), mFragments);
        mViewPager.setSupportScroll(true);
        AppTab1 appTab = new AppTab1(getContext(), Utils.dpToPx(45, getResources()));
        appTab.setTextColor(getResources().getColor(R.color.app_theme_color1), Color.parseColor("#C7C7CC"));
        appTab.setLineWidth(Utils.dpToPx(15, getResources()));
        appTab.initPosition(mViewPager, mImgLine, mTags);

        mViewPager.setCurrentItem(0, true);
    }

    private void initFragment() {
        mFragments[0] = new TeamCenterDetailMonthOrderNumFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putInt("type", 0);
        bundle1.putInt("teamId", teamId);
        mFragments[0].setArguments(bundle1);
        //
        Bundle bundle2 = new Bundle();
        bundle2.putInt("type", 1);
        bundle2.putInt("teamId", teamId);
        mFragments[1] = new TeamCenterDetailMonthOrderNumFragment();
        mFragments[1].setArguments(bundle2);
        //
        Bundle bundle3 = new Bundle();
        bundle3.putInt("type", 2);
        bundle3.putInt("teamId", teamId);
        mFragments[2] = new TeamCenterDetailMonthOrderNumFragment();
        mFragments[2].setArguments(bundle3);
    }

    @Override
    public void onClick(View v) {
        if (teamId <= 0) {
            return;
        }
        Intent intent = null;
        switch (v.getId()) {
            //过往成就
            case R.id.old_achievement_tv:
                intent = new Intent(getContext(), CourierTeamPastAchievementsActivity.class);
                intent.putExtra("teamId", teamId);
                startActivity(intent);
                break;
            //队员申请列表
            case R.id.team_applylist_layout:
                intent = new Intent(getContext(), CourierTeamMemberApplyListActivity.class);
                intent.putExtra("teamId", teamId);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRequest) {
            showLoadingDialog(null);
            AppHttp.getInstance().getTeamDetail(teamId);
            if (mViewPager != null) {
                ((TeamCenterDetailMonthOrderNumFragment) mFragments[mViewPager.getCurrentItem()]).refreshData(teamId, mViewPager.getCurrentItem());
            }
        }
        isRequest = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRequest = true;
    }

    /**
     * 根据数据更新布局
     */
    private void updateViewForData(CourierTeamDetailBackBean detailBackBean) {
        if (detailBackBean == null) {
            return;
        }
        type = detailBackBean.getTeamStatus() - 1;
        if (type == 1) {
            mOldAchievementTV.setVisibility(View.VISIBLE);
            mOldAchievementTV.setOnClickListener(this);
            mCreatingTeamLayout.setVisibility(View.GONE);
            mOperateTeamLayout.setVisibility(View.VISIBLE);
        } else {
            mOldAchievementTV.setVisibility(View.GONE);
            mCreatingTeamLayout.setVisibility(View.VISIBLE);
            mOperateTeamLayout.setVisibility(View.GONE);
        }
        //战队名称
        ((TextView) findViewById(R.id.team_detail_name_tv)).setText(detailBackBean.getTeamName());
        //队长头像
        GlideUtil.loadImage(getContext(), detailBackBean.getImagePath(), R.drawable.setting_head_hover_default, (CircularImage) findViewById(R.id.team_leader_iv));
        //队长相关信息 萨尔（王师傅） 2011-11-11 创建
        if (isEmpty(detailBackBean.getName())) {
            ((TextView) findViewById(R.id.team_leader_info_tv)).setText(detailBackBean.getNickName() + "（" + detailBackBean.getName() + "）" + DateUtils.getTimeYMDHMSFormat().format(detailBackBean.getTeamCreateTime()).split(" ")[0] + " 创建");
        } else {
            ((TextView) findViewById(R.id.team_leader_info_tv)).setText(detailBackBean.getNickName() + "（" + detailBackBean.getName().substring(0, 1) + "师傅）" + DateUtils.getTimeYMDHMSFormat().format(detailBackBean.getTeamCreateTime()).split(" ")[0] + " 创建");
        }
        if (detailBackBean.isMemberFlag()) {
            //处理队长消息布局
            if (detailBackBean.isTeamLeader()) {
                findViewById(R.id.team_applylist_layout).setVisibility(View.VISIBLE);
                if (detailBackBean.isCheckFlag()) {
                    findViewById(R.id.courier_new_message_iv).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.courier_new_message_iv).setVisibility(View.GONE);
                }
                getAppTitle().setCommonTitle("战队中心", new TitleRes("解散", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (teamId > 0) {
                            DialogMgr.teamDissolveDialog(getContext(), teamId);
                        }
                    }
                }));
            } else {
                if (type == 1) {
                    getAppTitle().setCommonTitle("战队中心", new TitleRes("退出", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (teamId > 0) {
                                DialogMgr.teamExitDialog(getContext(), teamId);
                            }
                        }
                    }));
                } else {
                    getAppTitle().setCommonTitle("战队中心");
                }

                findViewById(R.id.team_applylist_layout).setVisibility(View.INVISIBLE);
            }
        } else {
            getAppTitle().setCommonTitle("战队中心");
        }
        if (type == 1) {
            //总单量
            ((TextView) findViewById(R.id.detail_total_order_top_tv)).setText(detailBackBean.getTaskCountTop() + "");
            ((TextView) findViewById(R.id.detail_total_order_num_tv)).setText("共" + detailBackBean.getTaskCount() + "单");
            //总里程
            ((TextView) findViewById(R.id.detail_total_distance_top_tv)).setText(detailBackBean.getTaskDistinceTop() + "");
            ((TextView) findViewById(R.id.detail_total_distance_tv)).setText("共" + detailBackBean.getTaskDistince() + "公里");
            //总收入
            ((TextView) findViewById(R.id.detail_total_money_top_tv)).setText(detailBackBean.getTaskProfitTop() + "");
            ((TextView) findViewById(R.id.detail_total_money_tv)).setText("共收入" + detailBackBean.getTaskProfit() + "元");
        } else {
            //组队中
            final TextView dayTV = findViewById(R.id.team_detail_day_tv);
            final TextView hourTV = findViewById(R.id.team_detail_hour_tv);
            final TextView minuteTV = findViewById(R.id.team_detail_minute_tv);
            long diffTime = detailBackBean.getTeamCancelTime() - System.currentTimeMillis();
            remaintimeCountdown(dayTV, hourTV, minuteTV, diffTime);
            timer = new CountDownTimer(diffTime, 60 * 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    remaintimeCountdown(dayTV, hourTV, minuteTV, millisUntilFinished);
                }

                @Override
                public void onFinish() {
                }
            };
            timer.start();
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //详情返回的数据，包含列表的数据
            case MsgID.courier_team_detail:
                cancelLoadingDialog();
                final ReqResult<CourierTeamDetailBackBean> reqResult = JSON.parser(msg.obj, CourierTeamDetailBackBean.class);
                if (checkLoginStatus(reqResult)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateViewForData(reqResult.getResult());
                        }
                    });
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            //解散或退出战队
            case MsgID.courier_team_cancel:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    finish();
                } else {
                    showToast(result.getMessage());
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private void remaintimeCountdown(TextView dayTV, TextView hourTV, TextView minuteTV, long remainTime) {
        String[] diffs = AppLogic.timeDiffDHMSStr(remainTime);
        String timeText = "";
        if (diffs.length == 0) {
            timeText = "00 天 00 小时 00 分";
            dayTV.setText("00");
            hourTV.setText("00");
            minuteTV.setText("00");
        } else if (diffs.length == 1) {
            timeText = "00 天 00 小时 00 分";
            dayTV.setText("00");
            hourTV.setText("00");
            minuteTV.setText("00");
        } else if (diffs.length == 2) {
            timeText = "00 天 " + "00 小时 " + diffs[0] + " 分";
            dayTV.setText("00");
            hourTV.setText("00");
            minuteTV.setText(diffs[0] + "");
        } else if (diffs.length == 3) {
            timeText = "00 天 " + diffs[0] + " 小时 " + diffs[1] + " 分";
            dayTV.setText("00");
            hourTV.setText(diffs[0] + "");
            minuteTV.setText(diffs[1] + "");
        } else if (diffs.length == 4) {
            timeText = diffs[0] + " 天 " + diffs[1] + " 小时 " + diffs[2] + " 分";
            dayTV.setText(diffs[0] + "");
            hourTV.setText(diffs[1] + "");
            minuteTV.setText(diffs[2] + "");
        }
    }

    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }
}
